package com.ph.shopping.facade.member.service.dbservice.facade.impl;

import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ph.shopping.common.core.base.BaseService;
import com.ph.shopping.common.core.customenum.MemberEnum;
import com.ph.shopping.common.core.customenum.ResultEnum;
import com.ph.shopping.common.util.container.ContainerUtil;
import com.ph.shopping.common.util.http.HttpClientObject;
import com.ph.shopping.common.util.page.PageBean;
import com.ph.shopping.common.util.result.Result;
import com.ph.shopping.facade.duboresult.DubboResult;
import com.ph.shopping.facade.mapper.MemberAuthMapper;
import com.ph.shopping.facade.mapper.MemberMapper;
import com.ph.shopping.facade.member.dto.CheckMemberAuthDto;
import com.ph.shopping.facade.member.dto.MemberAuthDto;
import com.ph.shopping.facade.member.dto.QueryMemberAuthDto;
import com.ph.shopping.facade.member.entity.Member;
import com.ph.shopping.facade.member.entity.MemberAuth;
import com.ph.shopping.facade.member.service.dbservice.facade.IMemberAuthDbService;
import com.ph.shopping.facade.member.vo.MemberAuthVo;
import com.ph.shopping.facade.util.MD5Util;

/**
 * @项目：phshopping-service-member
 * @描述：
 * @作者： Mr.zheng
 * @创建时间：2017-3-16
 * @修改者：lijie
 * @修改时间：2017-04-19
 * @Copyright @2017 by Mr.zheng
 */
@Service
public class MemberAuthDbService extends BaseService implements IMemberAuthDbService {

    private static Logger logger = LoggerFactory.getLogger(MemberAuthDbService.class);

    @Autowired
    MemberAuthMapper memberAuthMapper;

    @Autowired
    MemberMapper memberMapper;

    @Value("${xyt_server}")
    private String xytServer;

    @Value("${xyt_server_bd}")
    private String xytServerBd;

    /**
     * 推广师申请
     * @param memberAuthDto
     * @return
     */
	@Transactional
	@Override
	public Result apply(MemberAuthDto memberAuthDto) {
		// 判断是否已存 如果不存在则新增，存在未通过则修改，反之则表示存在 ，flag = true 表示存在执行修改操作
		boolean flag = false;
		// 判断是否已经是推广师
		MemberAuth auth = memberAuthMapper.selectMemAuthByMemId(memberAuthDto.getMemberID());
		if (null != auth) {
			flag = MemberEnum.PROMOTION_FAIL.getCode().equals(auth.getStatus());
			if (!flag) {
				return DubboResult.getResultByEnum(ResultEnum.MEMBERAUTH_EXIST);
			}
		}
		// 判断账号是否被授权
		auth = memberAuthMapper.selectMemAuthByAcc(memberAuthDto.getAccount());
		if (null != auth) {
			flag = MemberEnum.PROMOTION_FAIL.getCode().equals(auth.getStatus());
			if (!flag) {
				return DubboResult.getResultByEnum(ResultEnum.ACCOUNT_EXIST);
			}
		}
		String url = xytServer;
		url = MemberEnum.PROMOTION_LOCAL.getCode().equals(memberAuthDto.getAccountType()) ? xytServerBd : url;
		// 调用接口校验
		if (!checkAccount(memberAuthDto, url, memberAuthDto.getAccountType())) {
			// 校验失败
			return DubboResult.getResultByEnum(ResultEnum.ACCOUNT_VILIDATE_ERROR);
		}
		MemberAuth memberAuth = new MemberAuth();
		BeanUtils.copyProperties(memberAuthDto, memberAuth);
		// 本地保存
		memberAuth.setStatus(MemberEnum.PROMOTION_AUDIT.getCode());
		if (flag) {// 修改操作
			memberAuth.setId(auth.getId());
			memberAuth.setUpdateTime(new Date());
			memberAuthMapper.updateByPrimaryKeySelective(memberAuth);
		} else {// 新增操作
			memberAuth.setIsDelete(MemberEnum.PROMOTION_NORMAL.getCode());
			memberAuth.setCreateTime(new Date());
			memberAuthMapper.insert(memberAuth);
		}

		return DubboResult.getResultByEnum(ResultEnum.SUCCESS);
	}

    /**
     * 审核推广师
     * @param checkMemberAuthDto
     * @return
     */
    @Transactional
    @Override
    public Result check(CheckMemberAuthDto checkMemberAuthDto) {
        MemberAuth memberAuth = new MemberAuth();
        memberAuth.setMemberID(checkMemberAuthDto.getMemberID());
        memberAuth.setStatus(checkMemberAuthDto.getStatus().byteValue());
        memberAuth.setUpdateTime(new Date());
        if (checkMemberAuthDto.getStatus().intValue() == 2) {
            //修改会员表中推广师字段,设置成1--推广师
            Member member = new Member();
            member.setId(checkMemberAuthDto.getMemberID());
            member.setUpdateTime(new Date());
            member.setIsMarketing(MemberEnum.IS_MARKETING_BYYES.getCode());
            memberMapper.updateMember(member);
            //通过需要修改通过时间
            memberAuth.setPassTime(new Date());
        }
        memberAuthMapper.updateStatus(memberAuth);
        return DubboResult.getResultByEnum(ResultEnum.SUCCESS);
    }

    /**
     * 新业态和本地推广师接口校验
     * @param memberAuthDto
     * @param url
     * @return
     */
	private boolean checkAccount(MemberAuthDto memberAuthDto, String url, Byte type) {
		boolean flag = false;
		try {
			List<NameValuePair> callParams = getCheckAccountData(memberAuthDto, type);
			if (callParams == null || callParams.isEmpty()) {
				return flag;
			}
			logger.info("推广师账户校验请求地址url={},callParams={}", url, JSON.toJSONString(callParams));
			String checkResult = HttpClientObject.sendPost(url, callParams);
			logger.info("推广师账户校验请求返回值,checkResult={}", JSON.toJSONString(checkResult));
			if(StringUtils.isNotBlank(checkResult)){
				JSONObject jsonObj = JSON.parseObject(checkResult);
				Object state = jsonObj.get("state");
				Object data = jsonObj.get("data");
				if (state != null && data != null) {
					flag = "0".equals(state.toString()) && "0000".equals(data.toString());
				}
			}
		} catch (Exception ex) {
			logger.error("推广师账户校验异常,ex={}", ex);
		}
		return flag;
	}

    /**
     * 
     * @Title: getCheckAccountData   
     * @Description: 封装验证推广师参数  
     * @param: @param memberAuthDto
     * @param: @param type
     * @param: @return      
     * @return: List<NameValuePair>      
     * @throws
     */
	private List<NameValuePair> getCheckAccountData(MemberAuthDto memberAuthDto, Byte type) {
		List<NameValuePair> result = ContainerUtil.aList();
		String password = memberAuthDto.getPassword();
		String account = memberAuthDto.getAccount();
		if (MemberEnum.PROMOTION_XYT.getCode().equals(type)) {
			result.add(new BasicNameValuePair("mobile", account));
			result.add(new BasicNameValuePair("serviceName", "VerifyPromotionDivision"));
			String passwordMd5 = MD5Util.MD5Encode(password, "utf-8");
			String valid = MD5Util.MD5Encode(account + passwordMd5, "utf-8");
			result.add(new BasicNameValuePair("valid", valid));
		} else if (MemberEnum.PROMOTION_LOCAL.getCode().equals(type)) {
			result.add(new BasicNameValuePair("mobile", account));
			result.add(new BasicNameValuePair("serviceName", "VerifyPromotionDivision"));
			String valid = MD5Util.MD5Encode("ystbd" + account, "utf-8");
			result.add(new BasicNameValuePair("newvalid", valid));
		}
		return result;
	}
    /**
     * 推广师列表查询
     */
	@Override
	public Result getMemberAuthListByPage(PageBean page,QueryMemberAuthDto queryMemberAuthDto) {
		PageHelper.startPage(page.getPageNum(), page.getPageSize());
		List<MemberAuthVo> list = memberAuthMapper.selectMemAuthList(queryMemberAuthDto);
		PageInfo<MemberAuthVo>pageInfo=new PageInfo<MemberAuthVo>(list);
		return getResult(ResultEnum.SUCCESS,pageInfo.getList(),pageInfo.getTotal());
	}

	/**
	 * 删除推广师
	 * @param memberAuth
	 * @return
	 */
	@Override
	public Result deleteMemAuthByMemId(MemberAuth memberAuth) {
		memberAuthMapper.deleteMemberAuth(memberAuth);
		return DubboResult.getResultByEnum(ResultEnum.SUCCESS);
	}
	
	/**
	* 
	* @Title: getMemberAuthListByPage  
	* @Description: 获取推广师集合
	* @param queryMemberAuthDto
	* @return Result    返回类型  
	* @throws
	*/
	@Override
	public Result getMemberAuthList(QueryMemberAuthDto queryMemberAuthDto) {
		List<MemberAuthVo> list = memberAuthMapper.selectMemAuthList(queryMemberAuthDto);
		return getResult(ResultEnum.SUCCESS,list);
	}

	@Override
	public Result queryMemberAuthInfo(Long memberId) {
		Result result = DubboResult.getDefResultByImpl();
		MemberAuth memberAuth = memberAuthMapper.selectMemAuthByMemId(memberId);
		if (memberAuth != null) {
			result.setData(memberAuth);
			result = DubboResult.getResultBySuccess(result);
		}
		return result;
	}
	
}
